package com.sqly.doc.menu.zyy;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.IdRes;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sqly.doc.R;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.grjbxx.jm_info_add;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.Selected;
import com.sqly.doc.pojo.Zytzbs;
import com.sqly.doc.user.choose_user;
import com.sqly.doc.util.BinderPojo;
import com.sqly.doc.util.BinderUtil;
import com.sqly.doc.util.CreateBitmap;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.Url;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.util.WriteActivity;
import com.sqly.doc.view.CustomDatePicker;
import com.sqly.doc.view.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

//import cn.pedant.SweetAlert.SweetAlertDialog;
import com.cazaea.sweetalert.SweetAlertDialog;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/11/22 0022.
 */

public class zyy_tzcs_bak extends MyBaseActivity {

    List<String> list;//信息列表
    ListView listView;
    //标题
    TextView title, uname;
    Context con = zyy_tzcs_bak.this;
    private CustomDatePicker customDatePicker;

    @BinderPojo(value = R.id.SFJLH, name = "SFJLH", pojoProperty = true)
    private TextView SFJLH;

    @BinderPojo(value = R.id.XINGMING, name = "XINGMING", pojoProperty = true, require = true, promptMsg = "请选择患者信息")
    private TextView XINGMING;

    @BinderPojo(value = R.id.SFRQ, name = "SFRQ", pojoProperty = true, require = true, promptMsg = "请选择填表日期")
    private TextView SFRQ;

    Zytzbs obj;
    boolean isadd=false;//是否是新添加
    String url="",JKDAH="";
    ImageView sfysqm, brqm, xcqm;
    String sfysqmpic = "", brqmpic = "",xcqmpic ="";
    List<Selected> slist = new ArrayList<>();
    JuMin j;

    @Override
    protected void initUI() {
        setContentView(R.layout.zyy_jkglfw);

        BinderUtil.exeFindById(zyy_tzcs_bak.this);
        if (NetWorkUtils.isNetworkConnected(con)) {
            if (getIntent().getStringExtra("type").equals("edit")) {
                obj = (Zytzbs) getIntent().getExtras().getSerializable("b");
                init(obj);
                brqm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                sfysqm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                if (!StringUtils.isEmpty(obj.getImg())) {
                    brqmpic = obj.getImg();
                    ImageLoader.getInstance().displayImage(Url.img_url() + obj.getImg(), brqm);
                }
                if (!StringUtils.isEmpty(obj.getImg1())) {
                    sfysqmpic = obj.getImg1();
                    ImageLoader.getInstance().displayImage(Url.img_url() + obj.getImg1(), sfysqm);
                }
            }else {
                obj = new Zytzbs();
                init(obj);
            }

        }

    }

    private void init(final Zytzbs obj){
        //运行时生成activity中所有控件的findViewById方法
        //BinderUtil.exeFindById(fjhdycrhsf.this);
        BinderUtil.initData(zyy_tzcs_bak.this, obj);
        //标题
        sfysqm = (ImageView) findViewById(R.id.sfysqm);
        if (obj != null && !StringUtils.isEmpty(obj.getSfysqm())) {
            sfysqmpic = obj.getSfysqm();
            sfysqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + sfysqmpic + ".jpg"));
        }
        sfysqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, WriteActivity.class).putExtra("class", "jsb_xxbc.class"), 8);
            }
        });
        brqm = (ImageView) findViewById(R.id.brqm);
        if (obj != null && !StringUtils.isEmpty(obj.getBrqm())) {
            brqmpic = obj.getBrqm();
            brqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
        }
        brqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, WriteActivity.class).putExtra("class", "jsb_xxbc.class"), 9);
            }
        });

        //姓名
        XINGMING = (TextView) findViewById(R.id.XINGMING);
        if (obj != null && !StringUtils.isEmpty(obj.getXINGMING())) {
            XINGMING.setText(obj.getXINGMING());
        }
        XINGMING.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NetWorkUtils.isNetworkConnected(con)) {
                    MyToastUtil.ShowToast(con, "联网失败！");
                }else {
                    Bundle bundle = getIntent().getExtras();
                    if (null != bundle.getString("type") && "add".equals(bundle.getString("type"))) {
                        startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "zyy_tzbs.class"), 1);
                    }
                }

            }
        });
        //填表日期
        SFRQ = (TextView) findViewById(R.id.SFRQ);
        if(obj != null && !StringUtils.isEmpty(obj.getSFRQ())){
            SFRQ.setText(obj.getSFRQ());
        }
        SFRQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        SFRQ.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(now);
            }
        });

        listView = (ListView) findViewById(R.id.listView);
        list = new ArrayList();
        list.add("(1)您精力充沛吗？指精神头足，乐于做事");
        list.add("(2)您容易疲乏吗？指体力如何，是否稍微活动一下或做一点家务劳动就感到累");
        list.add("(3)您容易气短，呼吸短促，接不上气吗？");
        list.add("(4)您说话声音低弱无力吗?指说话没有力气" );
        list.add("(5)您感到闷闷不乐、情绪低沉吗?指心情不愉快，情绪低落" );
        list.add("(6)您容易精神紧张、焦虑不安吗?指遇事是否心情紧张");
        list.add("(7)您因为生活状态改变而感到孤独、失落吗？" );
        list.add("(8)您容易感到害怕或受到惊吓吗?" );
        list.add("(9)您感到身体超重不轻松吗?(感觉身体沉重)[BMI指数＝体重kg/身高2m]");
        list.add("(10)您眼睛干涩吗?");
        list.add("(11)您手脚发凉吗?不包含因周围温度低或穿的少导致的手脚发冷");
        list.add("(12)您胃脘部、背部或腰膝部怕冷吗？指上腹部、背部、腰部或膝关节等，有一处或多处怕冷");
        list.add("(13)您比一般人耐受不了寒冷吗？指比别人容易害怕冬天或是夏天的冷空调、电扇等");
        list.add("(14)您容易患感冒吗?指每年感冒的次数");
        list.add("(15)您没有感冒时也会鼻塞、流鼻涕吗?");
        list.add("(16)您有口粘口腻，或睡眠打鼾吗？");
        list.add("(17)您容易过敏(对药物、食物、气味、花粉或在季节交替、气候变化时)吗?");
        list.add("(18)您的皮肤容易起荨麻疹吗? (包括风团、风疹块、风疙瘩)");
        list.add("(19)您的皮肤在不知不觉中会出现青紫瘀斑、皮下出血吗?指皮肤在没有外伤的情况下出现青一块紫一块的情况");
        list.add("(20)您的皮肤一抓就红，并出现抓痕吗?指被指甲或钝物划过后皮肤的反应");
        list.add("(21)您皮肤或口唇干吗?");
        list.add("(22)您有肢体麻木或固定部位疼痛的感觉吗？");
        list.add("(23)您面部或鼻部有油腻感或者油亮发光吗?指脸上或鼻子");
        list.add("(24)您面色或目眶晦黯，或出现褐色斑块/斑点吗?");
        list.add("(25)您有皮肤湿疹、疮疖吗？");
        list.add("(26)您感到口干咽燥、总想喝水吗？");
        list.add("(27)您感到口苦或嘴里有异味吗?指口苦或口臭");
        list.add("(28)您腹部肥大吗?指腹部脂肪肥厚");
        list.add("(29)您吃(喝)凉的东西会感到不舒服或者怕吃(喝)凉的东西吗？指不喜欢吃凉的食物，或吃了凉的食物后会不舒服");
        list.add("(30)您有大便黏滞不爽、解不尽的感觉吗?(大便容易粘在马桶或便坑壁上)");
        list.add("(31)您容易大便干燥吗?");
        list.add("(32)您舌苔厚腻或有舌苔厚厚的感觉吗?如果自我感觉不清楚可由调查员观察后填写");
        list.add("(33)您舌下静脉瘀紫或增粗吗？可由调查员辅助观察后填写");
        for (int i=1; i<=33; i++){
            Selected s = new Selected();
            s.setName("1");
            s.setPosition(11111);
            slist.add(s);
        }
        listView.setAdapter(new DealSettingAdapter(list));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle b=new Bundle();
                b.putSerializable("b",list.get(i));
                startActivity(new Intent(con, jm_info_add.class).putExtras(b));
            }
        });
        setListViewHeightBasedOnChildren(listView);


        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("老年人中医药健康管理服务记录");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean validate = BinderUtil.copyDataToView(zyy_tzcs_bak.this, obj);
                if(!validate){

                }else if (sfysqmpic.equals("") || brqmpic.equals("")) {
                    new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提示")
                            .setContentText("签名不能为空")
                            .show();
                } else if (NetWorkUtils.isNetworkConnected(con)) {  ///网络连接
                    RequestParams ps = BinderUtil.generateRequestParamsByView(zyy_tzcs_bak.this);
                    //RequestParams ps = new RequestParams();
                    if (isadd) {
                        ps.add("entity.JKDAH", JKDAH);
                        url = HttpUrl.SaveZytzbs;
                    } else {
                        ps.add("entity.SFJLH", obj.getSFJLH());
                        ps.add("entity.JKDAH", obj.getJKDAH());
                        url = HttpUrl.EditZytzbs;
                    }
                    for (int i=0; i<slist.size(); i++){
                        //ps.add("entity.HUBIE", obj.getHUBIE());
                        System.out.println(i+"=======>"+slist.get(i).getName());
                    }

                    ps.add("entity.XINGMING", obj.getXINGMING());
                    ps.add("entity.SFRQ", obj.getSFRQ());
                    ps.add("entity.CARDNUM", obj.getCARDNUM());
                    ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                    ps.add("type", "2");
                    if (isadd && !StringUtils.isEmpty(sfysqmpic)) {
                        try {
                            ps.put("img1", new File(Environment.getExternalStorageDirectory() + "/" + sfysqmpic + ".jpg"));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    if (isadd && !StringUtils.isEmpty(brqmpic)) {
                        try {
                            ps.put("img", new File(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }

                    UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                            String content = new String(response);
                            RetMsg ret = JSON.parseObject(content, RetMsg.class);
                            if (ret.getCode().equals("200")) {
                                MyToastUtil.ShowToast(con, "成功");
                            }else{
                                MyToastUtil.ShowToast(con, ret.getInfo());
                            }
                            finish();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                            MyToastUtil.ShowToast(con, "失败");
                        }
                    });
                } else {

                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else {
            if (requestCode == 1) {
                j = (JuMin) data.getExtras().getSerializable("j");
                getObject();
            }
            if (requestCode == 8) {

                byte[] bis = data.getByteArrayExtra("bitmap");
                Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
                Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
                sfysqm.setImageBitmap(bb);
                sfysqmpic = CreateBitmap.saveMyBitmap(bb);
            }
            if (requestCode == 9) {
                byte[] bis = data.getByteArrayExtra("bitmap");
                Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
                Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
                brqm.setImageBitmap(bb);
                brqmpic = CreateBitmap.saveMyBitmap(bb);
            }
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    
    public void getObject() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("CARDNUM", j.getCARDNUM());
        UserClient.get(HttpUrl.GetZytzbsGrjbxx, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    JSONObject j = JSON.parseObject(ret.getRd());
                    obj = new Zytzbs();
                    init(obj);
                    obj.setJKDAH(j.getString("JKDAH"));
                    obj.setXINGMING(j.getString("XINGMING"));
                    obj.setCARDNUM(j.getString("CARDNUM"));
                    JKDAH = j.getString("JKDAH");
                    XINGMING.setText(j.getString("XINGMING"));

                    isadd = true;
                } else {
                    SweetAlertDialogUtil.ErrorDialogNoFinish(con, "错误提示", ret.getInfo(), "确定");
                }

            }
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                isadd = true;
                obj = new Zytzbs();
                init(obj);
            }
        });
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    public class DealSettingAdapter extends BaseAdapter {
        private List<String> ll;
        public DealSettingAdapter(List<String> mArrayList) {
            this.ll = mArrayList;
        }

        @Override
        public int getCount() {
            return ll == null ? 0 : ll.size();
        }

        @Override
        public Object getItem(int position) {
            return ll == null ? null : ll.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            Selected s = slist.get(position);
            if (convertView == null) {
                convertView = View.inflate(con, R.layout.zyy_tzcs_item, null);
                holder = new ViewHolder();
                holder.xz = convertView.findViewById(R.id.xz);
                holder.wenti = convertView.findViewById(R.id.wenti);
                holder.my = convertView.findViewById(R.id.my);
                holder.hs = convertView.findViewById(R.id.hs);
                holder.ys = convertView.findViewById(R.id.ys);
                holder.jc = convertView.findViewById(R.id.jc);
                holder.zs = convertView.findViewById(R.id.zs);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String item = ll.get(position);
            holder.wenti.setText(item);
            if(position == 8){
                System.out.println("1position====>"+position+" item:"+item);
                holder.my.setText( "(BMI＜24)");
                holder.hs.setText("(24≤BMI＜25)");
                holder.ys.setText("(25≤BMI＜26)");
                holder.jc.setText("26≤BMI＜28" );
                holder.zs.setText("(BMI≥28)");
            }else if(position == 13){
                System.out.println("2position====>"+position+" item:"+item);
                holder.my.setText( "一年＜2次");
                holder.hs.setText("一年感冒2-4次");
                holder.ys.setText("一年感冒5-6次");
                holder.jc.setText("一年8次以上" );
                holder.zs.setText("几乎每月都感冒");
            }else if(position == 16){
                System.out.println("3position====>"+position+" item:"+item);
                holder.my.setText( "从来没有");
                holder.hs.setText("一年 1、2次");
                holder.ys.setText("一年 3、4次");
                holder.jc.setText("一年 5、6次" );
                holder.zs.setText("每次遇到上述原因都过敏");
            }else if(position == 27){
                System.out.println("4position====>"+position+" item:"+item);
                holder.my.setText( "腹围<80cm，相当于2.4尺");
                holder.hs.setText("腹围80-85c，2.4-2.55尺");
                holder.ys.setText("腹围86-90cm，2.56-2.7尺");
                holder.jc.setText("腹围91-105cm，2.71-3.15尺" );
                holder.zs.setText("腹围>105cm或3.15尺");
            }

            holder.xz.setTag(position);
            holder.xz.setOnCheckedChangeListener(null);
            holder.xz.clearCheck();
            if (s.getName()!=null && s.getName().equals("1"))
                holder.xz.check(holder.my.getId());
            else if (s.getName()!=null && s.getName().equals("2"))
                holder.xz.check(holder.hs.getId());
            else if (s.getName()!=null && s.getName().equals("3"))
                holder.xz.check(holder.ys.getId());
            else if (s.getName()!=null && s.getName().equals("4"))
                holder.xz.check(holder.jc.getId());
            else if (s.getName()!=null && s.getName().equals("5"))
                holder.xz.check(holder.zs.getId());

            final RadioGroup xz = holder.xz;
            holder.xz.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    System.out.println("position=================================>"+position);
                    if (checkedId == R.id.my)
                        slist.get((Integer) group.getTag()).setName("1");
                    if (checkedId == R.id.hs)
                        slist.get((Integer) group.getTag()).setName("2");
                    if (checkedId == R.id.ys)
                        slist.get((Integer) group.getTag()).setName("3");
                    if (checkedId == R.id.jc)
                        slist.get((Integer) group.getTag()).setName("4");
                    if (checkedId == R.id.zs)
                        slist.get((Integer) group.getTag()).setName("5");
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView wenti;
            RadioGroup xz;
            RadioButton my,hs,ys,jc,zs;
        }
    }
}
